const app = getApp()
const WXAPI = require("../../api/newApi")
const oldWXAPI = require("../../api/api")
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    useShow: {
      type: Boolean,
      value: false
    },
    projectLs: {
      type: Array,
      value: [],
    },
    resultObject: {
      type: Object,
      value: {},
    },
  },
  pageLifetimes: {
    show: function () {
      // 页面被展示
      console.log('222')
    },
    hide: function () {
      // 页面被隐藏
    },
    resize: function (size) {
      // 页面尺寸变化
    }
  },
  lifetimes: {
    attached: function () {
      // 在组件实例进入页面节点树时执行
      // console.log(this.properties.projectLs)
      // console.log(this.properties.resultObject)
      if (this.properties.projectLs.length > 0) {
        this.getServiceLs()
      }
    },
    detached: function () {
      console.log(111)
      // 在组件实例被从页面节点树移除时执行
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    qrcodeShow: false,
    serviceLs: [], //计次卡项目数组
    sumitLs: [], //核销项目数组
    cardfromInfo: { //核销提交参数
      customerCardId: '', //卡id
      verificationMoney: '', //实际核销金额（折扣后金额）
      totalMoney: '', //核销总金额（输入金额）
      verificationNum: '', //核销总次数（课时卡次数和计次卡次数）
      appCustomerCardNumberVerificationDTOList: [], //计次卡核销项目
    },
    verificationNum: '',
    totalMoney: '',
    discountNum: 0, //优惠金额（折扣后）
    actualNum: 0, //实际应付
    cardpayNum: 0, //会员卡支付金额
    differencePrice: 0, //需补差价
    isRepair: 0, //0不需要补差价   1：需要
    countdown: 60,
    orderId: '',
    deleteToken: false,
    anonymity: '2', //1 匿名用户 2 非匿名用户
    payFrom: { //微信支付提交参数
      payClient: '1', ////支付客户端 1 微信 2 支付宝
      merchantId: '', //商户id
      amount: '', //金额
      payAmount: '', //实际支付金额
      customerCouponId: '', //客户优惠券id（优惠券抵扣时传） 
      walletIds: [], //钱包id数组（使用积分抵扣时传）
      cardMoney: '',
      cardId: '', //   卡ID
      assetId: '', //资产id
      remark: '', //备注
      payScene: '1', //支付场景(微信支付时必传) 1 扫码支付 2 直接购买
      useWalletInfos: [],
      wxCode: '',
      giveMoney: 0, //赠送金额
      cardAssetId: '', //购买安心卡ID
      isActivity: false, //是否购买安心卡
      orderManageId: '', //去掉订单id
    },
    information: {},
    sumitShow: false, //核销确认弹窗
  },

  /**
   * 组件的方法列表
   */
  methods: {
    getServiceLs() { //获取项目
      this.data.serviceLs = this.properties.projectLs.map((item, index) => {
        item.isSelected = false
        item.addnum = 0
        return item
      })
      console.log(this.data.serviceLs)
      this.setData({
        serviceLs: this.data.serviceLs
      })
    },
    close() {
      this.setData({
        useShow: false,
        qrcodeShow: false,
      })
    },
    setChoice(e) {
      let item = e.currentTarget.dataset.item
      let index = e.currentTarget.dataset.index;
      // if (item.projectNumberUsable == 0) {
      //   wx.showToast({
      //     title: '该项目已用完',
      //     icon: 'none'
      //   })
      //   return
      // }
      // this.data.serviceLs[index].isSelected = !this.data.serviceLs[index].isSelected
      // this.setData({
      //   serviceLs: this.data.serviceLs
      // })
      // let checkls = this.data.serviceLs.filter((item, index) => {
      //   if (item.isSelected) {
      //     return true
      //   }
      //   return false
      // })
      // this.data.sumitLs = checkls
      console.log(this.data.sumitLs)
      // this.calculation()
    },
    gsetReduce(e) { //减少
      const index = e.currentTarget.dataset.index;
      let carts = this.data.serviceLs;
      let amount = carts[index].addnum;
      if (amount <= 0) {
        return false;
      }
      amount = amount - 1;
      carts[index].addnum = amount;
      this.setData({
        serviceLs: carts,
      });
      this.calculation()
    },
    getAdd(e) { //加
      const index = e.currentTarget.dataset.index;
      console.log(index)
      let amount = parseInt(this.data.serviceLs[index].addnum);
      if (amount >= this.data.serviceLs[index].projectNumberUsable) {
        return false;
      }
      amount += 1;
      this.data.serviceLs[index].addnum = amount;
      this.setData({
        serviceLs: this.data.serviceLs,
      });
      this.calculation()
    },
    calculation() { //计算
      let checkls = this.data.serviceLs.filter((item, index) => {
        if (item.addnum > 0) {
          return true
        }
        return false
      })
      console.log(checkls)
      var newAry = []
      checkls.forEach(item => {
        var obj = {}
        obj.id = item.id
        obj.projectName = item.projectName
        obj.useCount = item.addnum
        newAry.push(obj)
      })
      console.log('newAry', newAry)
      this.data.cardfromInfo.appCustomerCardNumberVerificationDTOList = newAry
    },
    setSumit() { //确认使用
      console.log(this.data.cardfromInfo)
      if (this.data.cardfromInfo.appCustomerCardNumberVerificationDTOList.length == 0) {
        wx.showToast({
          title: '请选择消费项目',
          icon: 'none'
        })
        return
      }
      let number = this.getTotalPrice(this.data.cardfromInfo.appCustomerCardNumberVerificationDTOList)
      console.log(number)
      this.data.cardfromInfo.verificationNum = number
      this.data.cardfromInfo.customerCardId = this.properties.resultObject.customerCardId
      wx.showLoading({
        title: '付款中',
      })
      var data = {
        ...this.data.cardfromInfo
      }
      WXAPI.writeoffCard(data, (res) => {
        if (res.code == 200) {
          console.log(res.result)
          this.triggerEvent('onScuess', res.result)
          wx.hideLoading()
        }
      })
    },
    getTotalPrice(arr) { //计算总数
      let carts = arr;
      let total = 0;
      for (let i = 0; i < carts.length; i++) {
        total += carts[i].useCount;
      }
      return Math.floor(total * 100) / 100
    },
    amountData(e) { //监听键盘输入
      console.log(e.detail)
      if (this.properties.resultObject.cardType == 4) {
        this.data.verificationNum = e.detail
      } else if (this.properties.resultObject.cardType == 1 || this.properties.resultObject.cardType == 3 || this.properties.resultObject.cardType == 6) {
        this.data.totalMoney = e.detail
        //判断折扣是否为空情况
        if (this.properties.resultObject.discount == '') {
          if (e.detail == '') {
            this.data.actualNum = 0
          } else {
            this.data.actualNum = e.detail
          }
          this.data.discountNum = 0
        } else {
          // let num = (this.properties.resultObject.discount / 10) * e.detail
          let num = app.mul(this.properties.resultObject.discount / 10,e.detail)
          this.data.actualNum = Math.round(num * 100) / 100
          this.data.discountNum = Math.round((e.detail - this.data.actualNum) * 100) / 100
        }
        this.data.cardfromInfo.verificationMoney = this.data.actualNum
        this.data.cardfromInfo.totalMoney = this.data.totalMoney
        // 判断是否需要补差价
        let balanceMoney = Math.round(this.properties.resultObject.balanceMoney * 100) / 100
        if (this.data.actualNum <= balanceMoney) { //不需要
          this.data.cardpayNum = this.data.actualNum
          this.data.differencePrice = 0
          this.data.isRepair = 0
        } else { //需要
          this.data.cardpayNum = this.properties.resultObject.balanceMoney
          this.data.differencePrice = Math.round((this.data.actualNum - this.data.cardpayNum) * 100) / 100
          this.data.isRepair = 1
        }
        console.log(typeof(this.data.differencePrice))
      }
      this.setData({
        verificationNum: this.data.verificationNum,
        totalMoney: this.data.totalMoney,
        actualNum: this.data.actualNum,
        discountNum: this.data.discountNum,
        cardpayNum: this.data.cardpayNum,
        differencePrice: this.data.differencePrice
      })
    },
    handlePay() { //确认
      if (this.properties.resultObject.cardType == 4) {
        this.getksPay()
      } else if (this.properties.resultObject.cardType == 2) {
        console.log('计次')
      } else {
        if (this.data.totalMoney == '') {
          wx.showToast({
            title: '请输入消费原价',
            icon: 'none'
          })
          return
        }
        if (this.data.differencePrice > 0 && !this.properties.resultObject.isOpenEveryday) {
          wx.showToast({
            title: '店铺尚未开通日常收款功能',
            icon: 'none'
          })
          return
        }
        // if (this.data.isRepair == 0) {
        //   this.getPay()
        // } else {
        //   this.wxPay()
        // }
        this.sumitPropClick()
      }
    },
    //自主核销确认弹窗
    sumitPropClick() {
      this.setData({
        sumitShow: true
      })
    },
    //自主核销确认弹窗关闭
    sumitPropClose() {
      this.setData({
        sumitShow: false
      })
    },
    //自主核销确认弹窗确认
    sumitPropConfirm() {
      if (this.data.isRepair == 0) {
        this.getPay()
      } else {
        this.wxPay()
      }
    },
    //创建订单
    wxPay() {
      this.data.payFrom.merchantId = this.properties.resultObject.merchantId
      this.data.payFrom.amount = this.data.totalMoney
      this.data.payFrom.payAmount = this.data.differencePrice
      this.data.payFrom.assetId = this.properties.resultObject.assetId
      this.data.payFrom.cardId = this.properties.resultObject.customerCardId
      this.data.payFrom.cardMoney = this.properties.resultObject.balanceMoney
      const that = this
      var data = {
        ...this.data.payFrom
      }
      console.log("创建订单", data)
      oldWXAPI.createOrder(data, (res) => {
        wx.showLoading({
          title: '支付中...',
          mask: 'true',
        })
        const data = res.result
        console.log("创建订单", res)
        if (res.code === 200) {
          this.data.orderManageId = res.result.orderManageId
          if (data.orderType == 1) {
            if (data.client == 1) {
              //微信支付
              wx.requestPayment({
                'timeStamp': data.timeStamp,
                'nonceStr': data.nonceStr,
                'package': data.package,
                'signType': data.signType, //MD5
                'paySign': data.paySign,
                'success': function (res) {
                  wx.hideLoading()
                  console.log('支付成功', res)
                  console.log(res)
                  if (res.errMsg == 'requestPayment:ok') {
                    wx.showToast({
                      title: '支付成功',
                    })
                    that.setData({
                      orderId: data.orderId
                    })
                    that.getCardPayorder()
                  }
                },
                'fail': function (res) {
                  that.cancelOrder()
                  wx.hideLoading({
                    success: (res) => {
                      wx.showToast({
                        title: '支付失败',
                        icon: 'none'
                      })

                    },
                  })
                  console.log('支付失败或取消支付', res)
                },
                'complete': function (res) {
                  console.log('支付完成', res)
                }
              })
            } else if (data.client == 2) {
              //支付宝
            }
          } else if (data.orderType == 2) {
            //0元订单
            wx.redirectTo({
              url: '/pages/pay/paySuccess/paySuccess?orderId=' + data.orderId + '&anonymity=' + that.data.anonymity + '&deleteToken=' + that.data.deleteToken,
            })
          }
        } else {
          wx.hideLoading()
          wx.showToast({
            title: res.message,
            icon: 'none'
          })
        }
      })
    },
    //购卡订单支付结果
    getCardPayorder() {
      const that = this
      console.log("that.data.anonymit", that.data.anonymit)
      this.setData({
        timer: setInterval(function () { //这里把setInterval赋值给变量名为timer的变量
          that.data.countdown--;
          var data = {
            orderId: that.data.orderId,
          }
          oldWXAPI.payResult(data, (res) => {
            const data = res.result
            console.log("获取支付结果", data.isPay)
            if (data.isPay) {
              wx.redirectTo({
                url: '/pages/pay/paySuccess/paySuccess?orderId=' + that.data.orderId + '&anonymity=' + that.data.anonymity + '&deleteToken=' + that.data.deleteToken,
              })
              clearInterval(that.data.timer);
            }
          })
          that.setData({
            countdown: that.data.countdown,
          })
          if (that.data.countdown == 0) {
            clearInterval(that.data.timer);
            that.setData({
              countdown: 60,
            })
          }
        }, 1000)
      })

    },
    //取消订单
    cancelOrder(e) {
      var that = this
      var data = {
        id: that.data.orderManageId
      }
      oldWXAPI.cancelOrder(data, (res) => {
        const data = res.result
        if (res.code === 200) {

        }
      })
    },
    getksPay() { //课时卡付款
      this.data.cardfromInfo.verificationNum = this.data.verificationNum
      this.data.cardfromInfo.customerCardId = this.properties.resultObject.customerCardId
      if (this.data.cardfromInfo.verificationNum == '') {
        wx.showToast({
          title: '请输入消费课时数目',
          icon: 'none'
        })
        return
      }
      wx.showLoading({
        title: '付款中',
      })
      var data = {
        ...this.data.cardfromInfo
      }
      WXAPI.writeoffCard(data, (res) => {
        if (res.code == 200) {
          this.triggerEvent('onScuess', res.result)
          wx.hideLoading()
        }
      })
    },
    getPay() { //股东卡、计费卡付款
      this.data.cardfromInfo.verificationMoney = this.data.actualNum
      this.data.cardfromInfo.totalMoney = this.data.totalMoney
      this.data.cardfromInfo.customerCardId = this.properties.resultObject.customerCardId
      wx.showLoading({
        title: '付款中',
      })
      var data = {
        ...this.data.cardfromInfo
      }
      WXAPI.writeoffCard(data, (res) => {
        if (res.code == 200) {
          this.triggerEvent('onScuess', res.result)
          wx.hideLoading()
        }
      })
    },
    codePay(e) { //直接付款
      let info = e.currentTarget.dataset.info;
      var aid = e.currentTarget.dataset.aid;
      var mid = e.currentTarget.dataset.mid;
      let isOpenEveryday = info.isOpenEveryday; //是否开通日常收款 ture 开通 false 未开通
      if (isOpenEveryday == false && (info.cardType == 1 || info.cardType == 3 || info.cardType == 6)) {
        wx.showToast({
          title: '店铺尚未开通日常收款功能',
          icon: 'none'
        })
        return
      }
      if (info.cardType == 2 || info.cardType == 4 || info.cardType == 5) {
        this.getcardUse(info.customerCardId)
      } else {
        wx.navigateTo({
          url: '/pages/pay/pay?assetId=' + aid + '&merchantId=' + mid,
        })
      }
    },
    getcardUse(e) { //立即使用
      wx.showLoading({
        title: '加载中',
      })
      let customerCardId = e
      var data = {
        customerCardId: customerCardId
      }
      WXAPI.customerAssetInfo(data, (res) => {
        if (res.code == 200) {
          wx.hideLoading()
          this.setData({
            information: res.result,
            qrcodeShow: true
          })
        }
      })
      setTimeout(() => {
        wx.hideLoading()
      }, 6000)
    },
  }
})